var app = angular.module("listApp", ['ngSanitize']),
	parid = UI.getParameterByName('parId');
var tay_time = UI.getTimes().times();

var timeout_json = function(data, $window) {
	if(data.returnCode == 999994) {
		var ss = 3;
		layer.msg(data.returnMessage + "！<strong class='Ajax_Out'>" + ss + "</strong> 秒后前往登录页", 50, -1);
		var picInt = setInterval(function() {
			if(ss >= 1) {
				ss = ss - 1;
				$('.Ajax_Out').text(ss);
			} else {
				clearInterval(picInt);
				try {
					$window.parent.location.href = data.returnData;
					$window.location.href = data.returnData;
				} catch(e) {
					log('timeout!')
				}
			}
		}, 1000);
		return false;
	}
}

app.config(function($httpProvider) {
	$httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
	$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
	$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
});

app.controller('tableCtrl', function($scope, $http, $window) {
	var vm = $scope.vm = {
			pageIndex: 1,
			pageSize: 10,
			title: '',
			content: '',
			source: '',
			startTime: '',
			endTime: '',
			url:'',
			seedType:'',
			id:''
		}
	var stpage = function(ii) {
		var jpage = [],
			index = vm.pageIndex,
			pcount = vm.pageSize,
			total = $scope.datas.totalRecords;
		len = 0,
			j = 0,
			pindex,
			tii = (ii - 1) / 2,
			sii = (ii - 1);
		if(total % pcount == 0) {
			len = total / pcount;
		} else {
			len = parseInt(total / pcount) + 1;
		}
		if(len >= ii) {
			if(index < ii) {
				for(var i = 1; i <= len; i++) {
					j++;
					if(j <= ii) jpage.push(i);
				}
			} else if(index >= len - sii) {
				var pindex = index < len - tii ? index - tii : len - sii;
				for(var i = pindex; i <= len; i++) {
					j++;
					if(j <= ii) jpage.push(i);
				}
			} else {
				for(var i = index - tii; i <= len; i++) {
					j++;
					if(j <= ii) jpage.push(i);
				}
			}
		} else {
			for(var i = 1; i <= len; i++) {
				jpage.push(i);
			}
		};
		$scope.pages_e = len;
		$scope.pages = jpage;
	}
	
	//传递URL的参数时，避免&符号后的字符串被截取
	$scope.URLencode = function(sStr){  
	    return sStr.replace(/\&/g,'%26');
//	    					.replace(/\+/g,'%2B')
//	    					.replace(/\"/g,'%22')
//	    					.replace(/\'/g,'%27')
//	    					.replace(/\%/g,'%25')
//	    					.replace(/\#/g,'%23')
//	    					.replace(/\&/g,'%26');  
	}
	
	$scope.domAjax = function(e, seedType, id,title) {
		var ids = '',
			de_id = id;
		$('.td .ui_checkbox.checked').each(function() {
			ids = ids + $(this).attr('data-id') + ',';
		});
		ids=(ids.substring(ids.length-1)==',')?ids.substring(0,ids.length-1):ids;
//		if(ids.length > 0) {
//			//删除多条
//			ids = ids.substr(0, ids.length - 1);
//			id = ids;
//			$('.layerInfoArea .jtit p').eq(0).text('是否删本条内容！');
//		}
		if((e === 'del') || (e === 'delAll')) {
//			if(!id) {
//				layer.msg('请选择至少一条数据！', 1, -1);
//				return false;
//			}
			$.layer({
				title: "温馨提示：",
				shade: [0],
				area: ['230', 'auto'],
				dialog: {
					msg: '确定删除吗？',
					btns: 2,
					type: -1,
					btn: ['确定', '取消'],
					yes: function() {
						$http.get(basePath + 'FinalDb/delete.do?seedType='+ seedType + '&id=' + id + '&title=' + title +'&vtimes=' + new Date().getTime()).success(function(data) {
							var j = timeout_json(data, $window);
							if(j == false) {
								return false;
							}
							layer.msg(data.returnMessage, 1, -1);
							setTimeout(function() {
								if(window.reLength==1&&vm['pageIndex']>1){
									$scope.setAjax({
										"pageindex" : vm['pageIndex']-1,
										"startTime":$('#start_t').val(),
										"endTime":$('#end_t').val()
									});
								}else{
									$scope.setAjax();
								}
							},1000);
						});
					},
					no: function() {}
				}
			});
		} else if(e == "list") {
			if(ids.length <= 0) {
				layer.msg('请您选中数据进行操作!', 1, -1);
				return false;
			}
			if($('.msg_class_table tr.td').length <= 0) {
				layer.msg('无数据！', 1, -1);
				return false;
			}
			vm['seedType']=$("#articleT").val();
			var url = basePath + 'FinalDb/exportExcelForPageData.do?listids=' + ids;
			if(vm.startTime!=undefined&&vm.startTime!="") url = url + '&publishTimeFrom='+ vm['startTime'];
			if(vm.endTime!=undefined&&vm.endTime!="") url = url + '&publishTimeTo='+ vm['endTime'];
			if(vm.title != undefined&&vm.title !="") url = url + '&title=' + encodeURIComponent(vm['title']);
			if(vm.content != undefined&&vm.content!="") url = url + '&content=' + encodeURIComponent(vm['content']);
			if(vm.url != undefined&&vm.url !="") url = url + '&url=' + encodeURIComponent(vm['url']);
			if(vm.source != undefined&&vm.source != "") url = url + '&source=' + encodeURIComponent(vm['source']);
			if(vm.seedType != undefined&&vm.seedType !="") url = url + '&seedType=' + vm['seedType'];

			//导出excel表格
			var win = window.open(url,"_self");
		} else if(e == "article") {
			if(ids.length <= 0) {
				layer.msg('请您选中数据进行操作!', 1, -1);
				return false;
			}
			vm['seedType']=$("#articleT").val();
			var url = basePath + 'FinalDb/exportWordForPageData?ids=' + ids;
			if(vm.startTime!=undefined&&vm.startTime!="") url = url + '&publishTimeFrom='+ vm['startTime'];
			if(vm.endTime!=undefined&&vm.endTime!="") url = url + '&publishTimeTo='+ vm['endTime'];
			if(vm.title != undefined&&vm.title !="") url = url + '&title=' + encodeURIComponent(vm['title']);
			if(vm.content != undefined&&vm.content!="") url = url + '&content=' + encodeURIComponent(vm['content']);
			if(vm.url != undefined&&vm.url !="") url = url + '&url=' + encodeURIComponent(vm['url']);
			if(vm.source != undefined&&vm.source != "") url = url + '&source=' + encodeURIComponent(vm['source']);
			if(vm.seedType != undefined&&vm.seedType !="") url = url + '&seedType=' + vm['seedType'];
			//导出word表格
			window.open(url,"_self");
		}
	}
	$scope.setAjax = function(obj) {
		if(obj) {
			vm["pageSize"] = obj.pagesize || vm["pageSize"];
			vm["pageIndex"] = obj.pageindex || vm["pageIndex"];
			//判断输入的页数是否大于最大的页数
			if(vm["pageIndex"]>$scope.pages_e&&$scope.pages_e>0){
				vm["pageIndex"]=$scope.pages_e;
			}
			vm["startTime"]= obj.startTime;
			vm["endTime"] = obj.endTime;
			vm["timestamp"]=obj.timestamp||vm["timestamp"];
		}
		$scope.addparid = parid;
		
		vm['seedType']=$("#articleT").val();
		url = basePath + 'FinalDb/queryList.do?sp=11&pageIndex=' + vm['pageIndex'] + '&pageSize=' + vm['pageSize'] + '&vtimes=' + new Date().getTime();
		if(vm.startTime!=undefined&&vm.startTime!="") url = url + '&publishTimeFrom='+ vm['startTime'];
		if(vm.endTime!=undefined&&vm.endTime!="") url = url + '&publishTimeTo='+ vm['endTime'];
		if(vm.title != undefined&&vm.title !="") url = url + '&title=' + encodeURIComponent(vm['title']);
		if(vm.content != undefined&&vm.content!="") url = url + '&content=' + encodeURIComponent(vm['content']);
		if(vm.url != undefined&&vm.url !="") url = url + '&url=' + $scope.URLencode(encodeURIComponent(vm['url']));
		if(vm.source != undefined&&vm.source != "") url = url + '&source=' + encodeURIComponent(vm['source']);
		if(vm.seedType != undefined&&vm.seedType !="") url = url + '&seedType=' + vm['seedType'];
		
		if((vm['startTime']==""&&vm['endTime']!="")||(vm['startTime']!=""&&vm['endTime']=="")){
			layer.msg('请输入完整的起止时间，或清空起止时间！', 3, -1);
			return false;
		}
	    var dLoading='';
	    $scope.dLoading=true;
	    $(".fuzzy").addClass("fuzzyCss");
		
		$http.get(url).success(function(data) {
			//获取本次返回数据的条数
			window.reLength = data.returnData.length;
			//取得当前页面的上一页、下一页
			$scope.prevIndex = parseInt($("#jsgo .cur").text())-1;
			$scope.nextIndex = parseInt($("#jsgo .cur").text())+1;
			
			var j = timeout_json(data, $window);
			if(j == false) {
				return false;
			}
			$('#zcont').removeClass('checked');
			$scope.datas = data;
			for(var i=0;i<$scope.datas.returnData.length;i++){
				if($scope.datas.returnData[i].seedType=="News"){
					$scope.datas.returnData[i].seedType="新闻";
				}
				if($scope.datas.returnData[i].seedType=="WeiXin"){
					$scope.datas.returnData[i].seedType="微信";
				}
				if($scope.datas.returnData[i].seedType=="Micro"){
					$scope.datas.returnData[i].seedType="微博";
				}
				if($scope.datas.returnData[i].seedType=="BBS"){
					$scope.datas.returnData[i].seedType="论坛";
				}
			}
			stpage(7);
			$scope.dLoading=false;
			$(".fuzzy").removeClass("fuzzyCss");
			if($scope.dLoading==false){
				if(data.returnData.length <= 0) {
					layer.msg('无数据！', 1, -1);
				}
			}
			$scope.keyInt="";
		});
	};
	//取得当天的时间
	function getNowFormatDate(t) {
	    var date = new Date();
	    var seperator1 = "-";
	    var seperator2 = ":";
	    var month = date.getMonth() + 1;
	    var strDate = date.getDate();
	    var strHour = date.getHours();
	    var strMin = date.getMinutes();
	    var strSec = date.getSeconds();
	    if (month >= 1 && month <= 9) {
	        month = "0" + month;
	    }
	    if (strDate >= 0 && strDate <= 9) {
	        strDate = "0" + strDate;
	    }
	    if (strHour >= 0 && strHour <= 9) {
	        strHour = "0" + strHour;
	    }
	    if (strMin >= 0 && strMin <= 9) {
	        strMin = "0" + strMin;
	    }
	    if (strSec >= 0 && strSec <= 9) {
	        strSec = "0" + strSec;
	    }
	    if(t==0){
	    	var curDate = date.getFullYear() + seperator1 + month + seperator1 + strDate
	            + " " + "00:00:00";
	    }else if(t==1){
	    	var curDate = date.getFullYear() + seperator1 + month + seperator1 + strDate
	            + " " + strHour + seperator2 + strMin + seperator2 + strSec;
	    }
	    return curDate;
	} 
	var curStartTime = getNowFormatDate(0);
	var curEndTime = getNowFormatDate(1);
	//初始化--刷新页面
	$scope.setAjax({
		"startTime" : curStartTime,
		"endTime" : curEndTime
	});
	//跳转
	$scope.goAjax = function(){
		$scope.setAjax({
			"pageindex": $scope.keyInt,
			"timestamp":$("#timestampInit").val(),
			"startTime":$('#start_t').val(),
			"endTime":$('#end_t').val()
		});
	}
	$scope.getAjax = function() {		
		vm['startTime'] = $('#start_t').val();
		vm['endTime'] = $('#end_t').val();
		
		var startV = Date.parse(new Date($('#start_t').val()));
		var endV = Date.parse(new Date($('#end_t').val()));
		var difTime = 31*24*60*60*1000;
		if(startV > endV) {
			layer.msg('发布时间区间错误！', 1, -1);
			return false;
		}
		if(endV-startV > difTime){
			$.layer({
				title: "温馨提示：",
				shade: [0],
				area: ['360', 'auto'],
				dialog: {
					msg: '建议起止时间维度不超过31天，是否仍将继续？',
					btns: 2,
					type: 0,
					btn: ['继续', '取消'],
					yes: function() {
						setTimeout(function() {
							$scope.setAjax({
								"pageindex": 1,
								"startTime":$('#start_t').val(),
								"endTime":$('#end_t').val()
							});
						});
						layer.closeAll('dialog');
					},
					no: function() {}
				}
			});
		}else{
			$scope.setAjax({
				"pageindex": 1,
				"startTime":$('#start_t').val(),
				"endTime":$('#end_t').val()
			});
		}
	}
	$(document).live('keyup', function(e) {
		e = e || window.event;
		if(e.keyCode == 13) {
			$scope.getAjax();
		}
	})
});
app.directive('pagen', function() { //页总数
	return {
		link: function($scope, ele) {
			ele.bind('click', function() {
				var pagesize = $(this).text();
				$(ele).addClass('cur').siblings().removeClass('cur');
				$scope.setAjax({
					"pagesize": pagesize,
					"pageindex": 1,
					"startTime":$('#start_t').val(),
					"endTime":$('#end_t').val()
				})
			})

		}
	}
});
app.directive('pageg', function() { //fenye
	return {
		link: function($scope, ele) {
			ele.bind('click', function() {
				var index = $(this).attr('data-href');
				/**
				 * 条件一：如果index为非数字，点击上一页，设为当前页码-1;
				 * 条件二：如果index为非数字，点击下一页，设为当前页码+1;
				 */
				if(isNaN(index) && $(this).attr('class')=="str"){
					index = parseInt($("#jsgo .cur").text())-1;
				}else if(isNaN(index) && $(this).attr('class')=="end"){
					index = parseInt($("#jsgo .cur").text())+1;
				}
				$scope.setAjax({
					"pageindex": index,
					"startTime":$('#start_t').val(),
					"endTime":$('#end_t').val()
				})
			})
		}
	}
});

$(function() {
	var pc_time = UI.getTimes();
	UI.message().base();
	laydate.skin('molv');
	$('.ui_select').each(function() {
		var _ = $(this),
			_a = _.find('.ui_s_t'),
			_c = _.find('.ui_s_bk'),
			_ca = _c.find('a');
		_a.live('click', function() {
			_c.slideToggle(200, "easeInSine");
		});
		_ca.live('click', function() {
			$(this).addClass('cur').siblings().removeClass('cur');
			_a.text($(this).text());
			$("#articleT").val($(this).attr("type"));
			_c.slideToggle(200, "easeInSine");
		});
		_c.live('mouseleave', function() {
			_c.stop(false, true).slideUp(200, "easeInSine");
		});
	});
	$('.ui_select').live('keyup', function(e) {
		var _ = $(this),
			b = _.find('.ui_s_bk'),
			di = 27;
		_.focus();
		e = e || window.event;
		var indx = b.find('a.cur').index() || 0;
		if(e.keyCode == 40) {
			var aindx = indx + 1,
				sct;
			if(rindx >= b.find('a').length) {
				rindx = b.find('a').length;
			}
			b.find('a').eq(aindx).addClass('cur').siblings('a').removeClass('cur');
			sct = aindx * di > 180 ? aindx * di - 80 : 0;
			b.scrollTop(sct);
		} else if(e.keyCode == 38) {
			var rindx = indx - 1,
				sct;
			sct = aindx * di > 100 ? aindx * di : 0;
			if(rindx <= 0) {
				rindx = 0;
			}
			b.find('a').eq(rindx).addClass('cur').siblings('a').removeClass('cur');
			sct = rindx * di > 180 ? rindx * di - 80 : 0;
			b.scrollTop(sct);
		} else if(e.keyCode == 13) {
			b.find('a.cur').trigger('click');
			_.blur();
			_.find('.ui_s_t').blur();
		}
		return false;
	});
	//时间范围--设置初始值
	$('#start_t').val(pc_time.start_ymd_hms);
	$('#end_t').val(pc_time.end_ymd_hms);
	$('#zcont').on('click', function() {
		$(this).toggleClass('checked');
		if($(this).attr('class').search('checked') > -1) {
			$('.td .ui_checkbox').addClass('checked');
		} else {
			$('.td .ui_checkbox').removeClass('checked');
		}
	});
	$('.td .ui_checkbox').live('click', function() {
		$(this).toggleClass('checked');
	});
	
	//只要有选项没被选中，那么全选就不会出现选中状态
	$(".td .ui_checkbox").live("click", function() {
		checkTrueFalse();
	});
	function checkTrueFalse() {
		var isTrue = true;
		$(".td .ui_checkbox").each(function() {
			var hasChecked = $(this).hasClass("checked");
			if(hasChecked == false) {
				isTrue = false;
				return;
			}
		});
		if(isTrue == false) {
			$("#zcont").removeClass("checked");
		} else {
			$("#zcont").addClass("checked");
		}
	}
	
	$('.tips').live('mouseenter', function() {
		layer.tips($(this).attr('data-tips'), this, {
			style: ['background-color:#fff; color:#666;padding:10px; font-size:13px;line-height:24px;', '#fff'],
			guide: 2,
			time: 5
		});
	});
	$('.tips').live('mouseleave', function() {
		$('.xubox_tips').remove()
	})
});